/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.model.Coin;
import com.click.app.model.Product;
import com.click.app.model.EntryProduct;
import com.click.app.model.EntryProductDetail;
import com.click.app.model.StorageProduct;
import com.click.app.model.Supplier;
import com.click.app.model.User;
import com.click.app.service.GenericManager;
import com.click.app.service.EntryProductManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Joel Chuca Condo
 */
public class EntryProductAction extends BaseAction {

    private EntryProductManager entryProductManager;
    private GenericManager<Coin, Long> coinManager;
    private GenericManager<StorageProduct, Long> storageProductManager;
    private GenericManager<Product, Long> productManager;
    private GenericManager<Supplier, Long> supplierManager;

    //private UserManager userManager;
    private EntryProduct entryProduct;
    private List suppliers;
    private List coins;
    private List entryProducts;
    private Long id;
    private boolean withDiscount;
    private boolean withBill;
    private boolean withCredit;
    private String dateMake;
    private String dateCredit;
    private Date todayDate;
    private HashMap reportParams;

    //DateFormatChanger changer = new DateFormatChanger();
    public void setCoinManager(GenericManager<Coin, Long> coinManager) {
        this.coinManager = coinManager;
    }

    public void setEntryProductManager(EntryProductManager entryProductManager) {
        this.entryProductManager = entryProductManager;
    }

    public void setStorageProductManager(GenericManager<StorageProduct, Long> storageProductManager) {
        this.storageProductManager = storageProductManager;
    }

    public void setProductManager(GenericManager<Product, Long> productManager) {
        this.productManager = productManager;
    }

    public void setSupplierManager(GenericManager<Supplier, Long> supplierManager) {
        this.supplierManager = supplierManager;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public EntryProduct getEntryProduct() {
        return entryProduct;
    }

    public void setEntryProduct(EntryProduct entryProduct) {
        this.entryProduct = entryProduct;
    }

    public List getEntryProducts() {
        return entryProducts;
    }

    public void setEntryProducts(List entryProducts) {
        this.entryProducts = entryProducts;
    }

    public List getCoins() {
        return coins;
    }

    public void setCoins(List coins) {
        this.coins = coins;
    }

    public boolean isWithBill() {
        return withBill;
    }

    public void setWithBill(boolean withBill) {
        this.withBill = withBill;
    }

    public boolean isWithCredit() {
        return withCredit;
    }

    public void setWithCredit(boolean withCredit) {
        this.withCredit = withCredit;
    }

    public boolean isWithDiscount() {
        return withDiscount;
    }

    public void setWithDiscount(boolean withDiscount) {
        this.withDiscount = withDiscount;
    }

    public Date getTodayDate() {
        return todayDate;
    }

    public void setTodayDate(Date todayDate) {
        this.todayDate = todayDate;
    }

    public String list() {
        //entryProductManager.suppliersReport(new Date(108,10,3), new Date(109,5,3));
        entryProducts = entryProductManager.getAll();
        return SUCCESS;
    }

    public String listPaid() {
        //entryProductManager.suppliersReport(new Date(108,10,3), new Date(109,5,3));
        entryProducts = getPaidEntryProducts();
        return SUCCESS;
    }

    public String listUnpaid() {
        //entryProductManager.suppliersReport(new Date(108,10,3), new Date(109,5,3));
        entryProducts = getUnpaidEntryProducts();
        return SUCCESS;
    }

    public String edit() {
        System.out.println(".......... Editing ..........");

        coins = coinManager.getAll();
        if (coins != null) {
            if (id != null) {
                entryProduct = entryProductManager.get(id);
            } else {
                entryProduct = new EntryProduct();
                entryProduct.setSupplier(new Supplier());
                entryProduct.setCoin(new Coin());
                Date n = new Date();
                entryProduct.setDate(n);
            }
            setConfigParams();
        } else {
            System.out.println(" suppliers is " + suppliers + " or coins is " + coins);
            return "error";
        }
        System.out.println("........... End Edit ..........");
        return SUCCESS;
    }

    public boolean validationPasses() {
        boolean vp = true;
        if (withBill) {
            if (entryProduct.getBill() == null || entryProduct.getBill().getCode().matches("")) {
                errorMessage("Product entry registration failed, required field[code].");
                vp = false;
            }
        }
        System.out.println("Validation finished: " + vp);
        return vp;
    }

    public String save() throws Exception {
        System.out.println("EntryProductAction -> save() ");
                if (!validationPasses()) {
            System.out.println("returning error...");
            return INPUT;
        }
        if (cancel != null) {
            return CANCEL;
        }

        boolean isNew = false;
        isNew = (entryProduct.getId() == null);

        if (entryProduct.getId() != null) {
            EntryProduct entryProductOld = entryProductManager.get(entryProduct.getId());
            entryProduct.setTotalPrice(entryProductOld.getTotalPrice());
            entryProduct.setDeleted(entryProductOld.getDeleted());

            if (entryProductOld.getBill() != null) {
                if (withBill) {
                    entryProduct.getBill().setId(entryProductOld.getBill().getId());
                    entryProduct.getBill().setDate(new Date());
                }
            }
        } else {
            entryProduct.setTotalPrice(0.0f);
            entryProduct.setDeleted(true);
        }

        //verifySetting();
        updateEntryProductUser();
        entryProduct = entryProductManager.save(entryProduct);
        getSession().setAttribute("entryProduct", entryProduct);

        System.out.println("EntryProductAction -> end save() ");

        if (!isNew) {
            saveMessage(getText("entryProduct.updated"));
            return INPUT;
        } else {
            saveMessage(getText("entryProduct.added"));
            return SUCCESS;
        }
    }

    public String delete() {
        List<EntryProductDetail> entryProductDetails = entryProductManager.get(entryProduct.getId()).getEntryProductDetails();
        entryProduct.setEntryProductDetails(entryProductDetails);
        for (EntryProductDetail pd : entryProductDetails) {
            StorageProduct storage = productManager.get(pd.getProduct().getId()).getStorageProduct();
            storage.decrementStok(pd.getQuantity());
            storageProductManager.save(storage);
        }
        entryProductManager.remove(entryProduct.getId());
        saveMessage(getText("entryProduct.deleted"));
        return "delete";
    }

    private void setConfigParams() {
        if (entryProduct.getBill() != null) {
            withBill = true;
        } else {
            withBill = false;
        }

    }

    private void verifySetting() {
        //config date
        //entryProduct.setDate(DateFormatChanger.changeStringtoDate(dateMake));

        // config entryProductBill
        if (withBill) {
            entryProduct.getBill().setDate(new Date());
            System.out.println("With bill ");
        } else {
            entryProduct.setBill(null);
            System.out.println("Without bill:");
        }

    // config timeCredit

    }

    private void updateEntryProductUser() {

        HttpServletRequest request = getRequest();

        String userName = request.getRemoteUser();
        List<User> users = userManager.getUsers(new User());
        //System.out.println(" 4 ***************************");
        for (Iterator<User> it = users.iterator(); it.hasNext();) {
            User user = it.next();
            if (user != null) {
                if (user.getUsername().equals(userName)) {
                    //entryProduct.setUser(user);
                    System.out.println(user);
                    return;
                }
            } else {
                System.out.println("user null");
            }
        }
        System.out.println("user null");
    }

    public String help() {
        return SUCCESS;
    }

    public String helpList() {
        return SUCCESS;
    }

    public List<EntryProduct> getUnpaidEntryProducts() {
        List<EntryProduct> unpaidEntryProducts = new ArrayList<EntryProduct>();
        for (EntryProduct p : entryProductManager.getAll()) {
        }
        return unpaidEntryProducts;
    }

    public List<EntryProduct> getPaidEntryProducts() {
        List<EntryProduct> paidEntryProducts = new ArrayList<EntryProduct>();
        for (EntryProduct p : entryProductManager.getAll()) {
        }
        return paidEntryProducts;
    }

    public String generateJasperReport() {
        System.out.println("generando reporte ...");
        reportParams = new HashMap();
        getReportParams().put("title", getText("entryProduct.heading"));
        getReportParams().put("supplier", getText("entryProduct.supplier.fullName"));
        getReportParams().put("total", getText("entryProduct.totalPrice"));
        getReportParams().put("date", getText("entryProduct.date"));
        return SUCCESS;
    }

    public HashMap getReportParams() {
        return reportParams;
    }

    public List<Supplier> getSuppliers() {
        return supplierManager.getAll();
    }
}

